/**
 * @description:
 * @file: utils.ts
 * @author: Evan
 * @date: 2025.04.08 09:42:30
 * @week: 周二
 * @version: V
 * */

import layout from '@/layout/index.vue'
import type { AsyncImportPages, RouteItem, PromiseComponent } from './type'
import type { RouteRecordRaw } from 'vue-router'

// 生产路由
const createRoutes = (pages: AsyncImportPages, components: PromiseComponent) => {
  const newPageComps: RouteItem[] = []
  const mk = '_'
  // 排序，防止层级错乱
  const list = Object.entries(pages).sort((a, b) => {
    const a1 = a[0].split('/').length
    const b1 = b[0].split('/').length
    return a1 - b1
  })

  // 对象装数组
  list.forEach(([path, meta]) => {
    let pageJs = path
    // 截取有效路由
    path = path.replace('../pages', '').replace('/page.js', '')
    path = path || '/'
    // 获取路由层级
    const names = path.split('/').filter(Boolean)
    const name = names.join(mk) || 'index'
    // 对应组件路径
    const compPath = pageJs.replace('page.js', 'index.vue')
    const cop: RouteItem = {
      path: path,
      component: components[compPath] as RouteRecordRaw['component'],
      name,
      meta,
      children: [],
      redirect: void 0
    }
    if (meta.redirect) {
      cop.redirect = meta.redirect
      delete meta.redirect
    }
    let parent: RouteItem, pi: number
    names.forEach((name: string, index: number) => {
      // 第一个为一级
      if (index == 0) {
        pi = newPageComps.findIndex(it => it.name == name)
        // 未找到则 push
        if (pi === -1) {
          // 深拷贝防污染
          const copy = { ...cop, children: [] } as RouteItem

          // 组件为空则使用布局组件
          if (!copy.component && !meta.notLayout) {
            copy.component = layout
          } else {
            // 默认一级添加布局组件，属性为真时则不处理
            if (!meta.notLayout) {
              // 一级且有组件
              copy.component = layout
              copy.name = void 0
              copy.children = [{ ...cop }]
            }
          }
          // 非一级目录
          if (names.length > 1) {
            copy.path = `/${name}`
            copy.name = name
          }
          newPageComps.push(copy)
          pi = newPageComps.length - 1
        }
        parent = newPageComps[pi]
      } else {
        // 没有子级 添加空数组
        if (!parent.children) {
          parent.children = []
        }
        const nm = names.slice(0, index + 1).join(mk)
        // 子级中查找层级未找到则添加
        const i = parent.children.findIndex(it => it.name == nm)
        if (i < 0) {
          parent.children.push(cop)
        } else {
          // 找到则接续添加到子级
          parent = parent.children[i]
        }
      }
    })
  })
  return newPageComps
}

// 动态导出 pages文件下路由配置
export const exportPagesRoutesConfig = () => {
  const pages = import.meta.glob('../pages/**/page.js', {
    eager: true, // 非异步
    import: 'default'
  }) as AsyncImportPages
  const pageComps = import.meta.glob('../pages/**/index.vue') as PromiseComponent
  return createRoutes(pages, pageComps)
}
